#!/usr/bin/env python

import BaseHTTPServer
import logging
import sys
import threading
import urlparse
import jamendo_downloader

FORM = '''<html><body>
<h1>Jamendo downloader</h1>

<p>%sCurrently <b>%d</b> URLs in queue.</p>
<br>

<form action="/jamendo/" method="POST">
  <input type="hidden" name="kind" value="artistname">
  Artist name: <input type="text" name="id">
  <input type="submit" name="submit" value="Fetch from artist name"
</form>
<br>

<form action="/jamendo/" method="POST">
  <input type="hidden" name="kind" value="artist">
  Artist ID: <input type="text" name="id">
  <input type="submit" name="submit" value="Fetch from artist ID"
</form>
<br>

<form action="/jamendo/" method="POST">
  <input type="hidden" name="kind" value="album">
  Album ID: <input type="text" name="id">
  <input type="submit" name="submit" value="Fetch from album ID"
</form>
<br>

<form action="/jamendo/" method="POST">
  <input type="hidden" name="kind" value="track">
  Track ID: <input type="text" name="id">
  <input type="submit" name="submit" value="Fetch from track ID"
</form>
<br>

</body></html>
'''

def parse_qs(qs):
    if not qs:
        return {}
    else:
        return dict(x.split('=', 1) for x in qs.split('&'))

class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def serve_form(self, message=""):
        data = FORM % (message, self.server.downloader.queue.qsize())
        self.send_response(200)
        self.send_header('Content-Type', 'text/html')
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if '?' in self.path:
            path, qs = self.path.split('?', 1)
        else:
            path, qs = self.path, ''
        if path != '/jamendo/':
            self.send_error(404, 'URL does not exist.')
            return
        params = parse_qs(qs)
        if 'ok' in params:
            if params['ok'] == '1':
                msg = 'Add successful. '
            else:
                msg = 'Add failed. '
        else:
            msg = ''
        self.serve_form(msg)

    def do_POST(self):
        if self.path != '/jamendo/':
            self.send_error(404, 'URL does not exist.')
            return
        if self.headers['Content-Type'] != 'application/x-www-form-urlencoded':
            self.send_error(400, 'Bad form data')
            return
        data = self.rfile.read(int(self.headers['Content-Length']))
        print data
        params = parse_qs(data)
        if self.server.downloader.add_smart(params['kind'], params['id']):
            ok = '1'
        else:
            ok = '0'
        self.send_response(303)
        self.send_header('Location', '/jamendo/?ok=' + ok)
        self.end_headers()


class PermanentDownloader(jamendo_downloader.Downloader):
    def start(self):
        t = threading.Thread(target=self.run)
        t.setDaemon(True)
        t.start()

    def should_stop(self):
        return False

def serve_web(downloader):
    addr = ('127.0.0.1', 8000)
    httpd = BaseHTTPServer.HTTPServer(addr, WebRequestHandler)
    httpd.downloader = downloader
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        sys.exit(0)

def main():
    logging.basicConfig(level=logging.INFO)
    downloader = PermanentDownloader(sys.argv[1])
    downloader.start()
    serve_web(downloader)

if __name__ == '__main__':
    main()
